package com.itheima.mp.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.Enum.UserStatus;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.query.PageQuery;
import com.itheima.mp.query.UserQuery;
import com.itheima.mp.service.Userservice;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author: XJH
 * @Description: TODO
 * @Date: 2025/6/13 20:27
 * @Version: 1.0
 */
@Service
@Transactional
public class UserserviceImpl extends ServiceImpl<UserMapper, User> implements Userservice {
    @Override
    public void deductBalance(Long id, Integer money) {
        // 1.查询用户
        User user = getById(id);
        // 2.判断用户状态
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常");
        }
        // 3.判断用户余额
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足");
        }
        // 4.扣减余额
//        baseMapper.deductMoneyById(id, money);
        Integer balance = user.getBalance() - money;
        lambdaUpdate()
        .set(User::getBalance, balance)
                .set(balance==0,User::getStatus,UserStatus.FROZEN)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())//锁 先比较再更新
                .update();


    }

    //lambdaUpdate 链式调用 
    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
       return lambdaQuery().like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();

    }

    @Override
    public UserVO queryUserandAddress(Long id) {
     //查询用户信息
         User user = getById(id);
        //查询用户地址信息
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        // 2.判断用户状态
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常");
        }
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        // 3.封装VO
        if(CollUtil.isNotEmpty(addresses)){
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;

    }

    @Override
    public List<UserVO> queryUserandAddressByIds(List<Long> ids) {
       // 一次性查询所有用户
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)) { // 修正判断逻辑：如果用户列表为空，直接返回空列表
            return Collections.emptyList();
        }

        // 一次性查询所有用户的地址
        List<Long> userIds = users.stream()
                .map(User::getId)
                .collect(Collectors.toList());

        List<Address> addresses = Db.lambdaQuery(Address.class)
                .in(Address::getUserId, userIds)
                .list();

        // 3. 将地址按用户ID分组
        Map<Long, List<Address>> addressMap = addresses.stream()
                .collect(Collectors.groupingBy(Address::getUserId));

        // 4. 封装VO对象
        List<UserVO> result = new ArrayList<>(users.size());
        for (User user : users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);

            // 设置用户对应的地址列表
            List<Address> userAddresses = addressMap.getOrDefault(user.getId(), Collections.emptyList());
            List<AddressVO> addressVOList = BeanUtil.copyToList(userAddresses, AddressVO.class);
            userVO.setAddresses(addressVOList);

            result.add(userVO);
        }

        return result;
    }

    @Override
    public PageDTO<UserVO> queryUserPage(UserQuery userQuery) {
        String name= userQuery.getName();
        Integer status= userQuery.getStatus();

//        //1.  分页查询条件
//        Page<User> page = Page.of(userQuery.getPageNo(), userQuery.getPageSize());
//        //2. 排序条件
//        if(StrUtil.isNotBlank(userQuery.getSortBy())){
//            page.addOrder(new OrderItem(userQuery.getSortBy(), userQuery.getIsAsc()));
//        }else{
//            page.addOrder(new OrderItem("update_time", false));
//        }
        Page<User> page = userQuery.toMpPageDefaultSortedByUpdateTime();

        //3.  分页查询用户
        Page<User> p = lambdaQuery().like(name != null, User::getUsername, userQuery.getName())
                .eq(status != null, User::getStatus, status)
                .page(page);

        //4. 封装VO对象

        //传统方式
//          PageDTO<UserVO> dto = new PageDTO<>();
//          dto.setTotal(p.getTotal());
//          dto.setPages(p.getPages());
//
//          List<User> records = p.getRecords();
//           if(CollUtil.isEmpty(records)){
//               dto.setList(Collections.emptyList());
//               return dto;
//           }
//           List<UserVO> list = BeanUtil.copyToList(records, UserVO.class);
//           dto.setList(list);

//        //stream
//        PageDTO<UserVO> dto = new PageDTO<>();
//          dto.setTotal(p.getTotal());
//          dto.setPages(p.getPages());
//        List<UserVO> userVOList = p.getRecords().stream().map(user -> BeanUtil.copyProperties(user, UserVO.class))
//                .collect(Collectors.toList());
//        //5. 封装分页结果
//          dto.setList(userVOList);
        return PageDTO.of(p,user -> {
            //自定义转换器
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
          vo.setUsername(user.getUsername().substring(0,vo.getUsername().length()-2)+"**");
          return vo;
        });


    }
}
